package com.hhw.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
public class JDBCController {

    @Autowired
//    引入Jdbc模板
            JdbcTemplate jdbcTemplate;

    //    查询所有数据库的所有信息
    @RequestMapping("/userList")
    public List<Map<String, Object>> userList() {
        String sql = "select * from user";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
        return maps;
    }
    /*新增的方法*/
    @RequestMapping("/addUser")
    public String  addUser(){
        String sql="insert into mybatis.user (id,username,password) values (4,'小明','123456')";
        jdbcTemplate.update(sql);
        System.out.println(sql+"执行完成");
        return "update-ok";
    }
    /*修改功能*/
/*    @RequestMapping("/updateUser")
    public String updateUser(){
        String sql="update mybatis.user set username='张小花' where id=4";
        jdbcTemplate.update(sql);
        System.out.println(sql);
        return "修改完成";
    }*/
    @RequestMapping("/updateUser/{id}")
    public String updateUser(@PathVariable("id") int id){
        String sql="update mybatis.user set username=?,password=? where id="+id;
//        数组封装一个操作对象
        Object[] objects = new Object[2];
        objects[0]="花花";
        objects[1]="abc111";
        jdbcTemplate.update(sql,objects);
        return "updateUser-ok";
    }

    /*删除功能*/
/*    @RequestMapping("delUser")
    public String delUser(){
        String sql=" delete from mybatis.user where id =4";
        jdbcTemplate.update(sql);
        return "成功删除"+sql;

    }*/

    //封装一个删除功能
    @RequestMapping("delUser/{id}")
    public String delUser(@PathVariable("id") int id){
        String sql="delete from mybatis.user where id="+id;
        jdbcTemplate.update(sql);
        return "delete-OK"+" "+sql;
    }
}